﻿using CBS.APP;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.FormPage
{
    /// <summary>
    /// AddTeacherRemuneration.xaml 的交互逻辑
    /// </summary>
    public partial class AddTeacherRemuneration : Window
    {
        public AddTeacherRemuneration()
        {
            InitializeComponent();
        }

        private async void BindSemester()
        {
            try
            {
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                }));
                cb_Semester.SelectedIndex = 0;

                cb_Type.SelectedIndex = 0;

                BindStudent();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void BindTeacher()
        {
            try
            {
                var list = await Task.Run(() => TeacherApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Teacher.ItemsSource = list;
                }));
                cb_Teacher.SelectedIndex = 0;
                //BindClassPlan();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void BindStudent()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                var list = await Task.Run(() => StudentSignUpApp.GetSelectList(semesterId));

                if (list.Count == 0)
                {
                    return;
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Student.ItemsSource = list;
                }));
                cb_Student.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            int studentId = ((StudentSelectModel)cb_Student.SelectedItem).StudentId;
            decimal payment = decimal.Parse(tb_Payment.Text.Trim());
            int payType = ((GeneralSelectModel)cb_Type.SelectedItem).Value;
            int teacherId = ((TeacherSelectModel)cb_Teacher.SelectedItem).TeacherId;

            DateTime? payTime = null;
            if (!string.IsNullOrWhiteSpace(tb_PayTime.Text.Trim()))
            {
                payTime = DateTime.TryParse(tb_PayTime.Text.Trim(), out DateTime tmp) ? tmp : null;
            }
            string payCode = string.Empty;
            string picBase64 = "";
            // 检查Image控件的Source属性是否为BitmapImage

            try
            {
                if (img_Pic.Source is BitmapImage bitmapImage)
                {
                    // 获取图片的Base64编码
                    picBase64 = GetBase64StringFromBitmapImage(bitmapImage);
                }

                var paymentModel = new StudentPaymentViewModel
                {
                    PaymentSemester = semesterId,
                    StudentId = studentId,
                    TeacherId = teacherId,
                    Payment = payment,
                    PaymentType = payType,
                    PaymentTime = payTime,
                    LogTime = DateTime.Now,
                    PaymentCode = payCode,
                    PaymentPic = picBase64,
                };

                if (StudentPaymentApp.CreateStudentPayment(paymentModel))
                {
                    this.DialogResult = true;
                }
                else
                {
                    //this.DialogResult= false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private string GetBase64StringFromBitmapImage(BitmapImage bitmapImage)
        {
            if (bitmapImage.UriSource == null) return "";

            string imagePath = bitmapImage.UriSource.LocalPath;
            using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[8];
                fs.Read(buffer, 0, buffer.Length);

                using MemoryStream memoryStream = new MemoryStream();
                BitmapEncoder encoder;
                // 判断文件头部字节
                if (buffer[0] == 0xFF && buffer[1] == 0xD8)
                {
                    encoder = new JpegBitmapEncoder(); // 选择合适的编码器，如JpegBitmapEncoder、PngBitmapEncoder等

                }
                else if (buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4E && buffer[3] == 0x47)
                {
                    encoder = new PngBitmapEncoder(); // 选择合适的编码器，如JpegBitmapEncoder、PngBitmapEncoder等
                }
                else
                {
                    return "";
                }
                encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
                encoder.Save(memoryStream);
                byte[] imageBytes = memoryStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }

        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BindStudent();
        }

        private void btn_Pic_Click(object sender, RoutedEventArgs e)
        {
            FileDialog dlg = new OpenFileDialog
            {
                Filter = "图像(*.jpg, *.jpeg, *.png, *.bmp)|*.jpg;*.jpeg;*.png;*.bmp",
                InitialDirectory = $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\CourseBillingSystem\\ExcelTemplate"
            };
            var result = dlg.ShowDialog();
            if (result.HasValue && result.Value)
            {
                // 创建BitmapImage并加载选中的图片文件
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(dlg.FileName);
                bitmap.CacheOption = BitmapCacheOption.OnLoad; // 确保图片在加载时被缓存
                bitmap.EndInit();

                // 将BitmapImage设置为Image控件的Source
                //imageControl.Source = bitmap;


                img_Pic.Source = bitmap;
            }
        }
    }
}
